// src/pages/department/index.tsx
import { Helmet } from "react-helmet";
import Header from "@shared/header";
import styles from "@styles/department.module.scss";
import classNames from "classnames";
import {useRequestDepartmentsQuery} from "@store/apiSlice/departmentApiSlice";
import {useEffect, useState} from "react";
import {useDispatch} from "react-redux";
import {useNavigate} from "react-router-dom";
import {saveConsult} from "@store/slices/consultSlice";


export default function Department() {
    // 发送请求获取科室
    const { data, isSuccess, isLoading } = useRequestDepartmentsQuery(undefined);
    //定义选中id
    const [id,setId] = useState<undefined | string>("6976485709309804544")
    //获取dispatch方法
    const dispatch = useDispatch();
    //获取页面跳转方法
    const navigate = useNavigate();
    useEffect(()=>{
        //患者列表没有获取成功
        if(!isSuccess) return;
        if(data.data.length===0){
            //清空id
            setId(undefined);}
        else {
            //默认选中第一个
            let selectPatient = data.data[0]
            setId(selectPatient.id)
        }
    },[isSuccess])
    return (
        <>
            <Helmet>
                <title>优医问诊-选择科室</title>
            </Helmet>
            <Header title="选择科室" />
            <div className={styles.page}>
                <div className={styles.left}>
                    {isSuccess && data.data.map((item)=>(
                        <span key={item.id} className={classNames(styles.item, {
                            [styles.active]: item.id === id
                        })}  onClick={()=>setId(item.id)}>{item.name}</span>
                    ))}

                </div>
                <div className={styles.right}>
                    {isSuccess && data.data.filter((item)=>item.id===id)[0].child.map((items)=>(
                        <span key={items.id} className={styles.item}  onClick={() => {
                            if (typeof id !== "undefined") {
                                // 保存患者 id
                                dispatch(saveConsult({ depId: items.id }));
                                // 页面跳转
                                navigate("/illness");
                            }
                        }}>{items.name}</span>
                    ))}

                </div>
            </div>
        </>
    );
}